import React, { useState, useRef, useEffect } from 'react';
import { Node } from '@tiptap/core'
import {Mp3, Mp3Attrs} from "../type";
import {produce} from "immer";
import StarterKit from '@tiptap/starter-kit';
import {EditorContent, mergeAttributes, ReactNodeViewRenderer, useEditor} from '@tiptap/react';
import { Paragraph } from '@tiptap/extension-paragraph'
import {WordView} from "./Paragraph/Word";
import History from '@tiptap/extension-history'
import Dropcursor from '@tiptap/extension-dropcursor'
import Bold from '@tiptap/extension-bold'
import Italic from '@tiptap/extension-italic'
interface Onclick{
    type:"word"|undefined
    pram: { [key: string]: any }
}
export const Mp3Player = ({ mp3}:{mp3:Mp3}) => {
    const mp3AttrsStore=useState<Mp3Attrs>({
        type:"mpeg",
        src:"/test/test.mp3",
        start:0,
        duration:0,//总时长（秒）
        currentTime:0,//当前时长（秒）
        a:0,
        b:10**8,
        paused:true,//是否暂停
        volume:1.0,//音量（0.0 到 1.0）
    })
    let mp3Attrs=mp3AttrsStore[0]
    let setMp3Attrs=(f:(mp3Attrs:Mp3Attrs)=>Mp3Attrs)=>{
        mp3AttrsStore[1](produce(mp3AttrsStore[0],(draft)=>{f(draft)}))
    }
    const audioRef = useRef<HTMLAudioElement>(null);
    const audio=audioRef.current

    const [dom,setDom]=useState<Onclick>({type:"word",pram:{start:0,end:0,word:""}})
    const [isOnclick,setIsOnclick]=useState<number>(0);


    const setCurrentTime = () => {
        if (audio){
            setMp3Attrs((mp3Attrs)=>{
                mp3Attrs.currentTime=audio.currentTime
                return mp3Attrs
            })
            if (mp3Attrs.currentTime>mp3Attrs.b) audio.currentTime = mp3Attrs.a
        }
    };


    useEffect(() => {
        if (audio) {
            audio.addEventListener('timeupdate', setCurrentTime);
        }

        return () => {
            if (audio) {
                audio.removeEventListener('timeupdate', setCurrentTime);
            }
        };
    }, [mp3Attrs]);


    useEffect(() => {
        if (audio){
            switch (dom.type){
                case "word":
                    audio.currentTime=dom.pram.start-1?dom.pram.start-0.2:0
                    break
            }
        }
    }, [isOnclick]);

    const editor = useEditor({
        // editable: false,
        extensions: [
            History, Dropcursor,
            Bold, Italic,
            Node.create({
                name: 'doc',
                topNode: true,
                content: 'word',
            }),
            Paragraph.extend({
                name: 'word',
                group: 'block',
                content: 'text*',
                renderHTML({ HTMLAttributes }) {
                    return ['word', mergeAttributes(HTMLAttributes), 0]
                },
                addAttributes() {
                    return {
                        start:0,
                        end:0
                    }
                },
                addNodeView() {
                    return ReactNodeViewRenderer(WordView)
                },
            }),
            Node.create({
                name: 'text',
                group: 'inline',
            }),
        ],
        content:mp3.lyric
    })

    return (
        <div className={"bg-gray-500 text-gray-950 w-full"}>
            <EditorContent editor={editor} className={"flex flex-row w-full"}/>
            <audio
                ref={audioRef}
                src={mp3.videoUrl}
                controls
            />
            <div className={"flex flex-row"}>
                <div
                    onClick={() => {
                        setMp3Attrs((mp3Attrs) => {
                            mp3Attrs.a = audio?.currentTime as number
                            return mp3Attrs
                        })
                    }}
                >
                    setA
                </div>
                <div>:{mp3Attrs.a}</div>
                <div
                    onClick={() => {
                        setMp3Attrs((mp3Attrs) => {
                            mp3Attrs.a = 0
                            return mp3Attrs
                        })
                    }}
                >clear
                </div>
            </div>
            <div className={"flex flex-row"}>
                <div
                    onClick={() => {
                        setMp3Attrs((mp3Attrs) => {
                            mp3Attrs.b = audio?.currentTime as number
                            return mp3Attrs
                        })
                    }}
                >
                    setB
                </div>
                <div>:{mp3Attrs.b}</div>
                <div
                    onClick={() => {
                        setMp3Attrs((mp3Attrs) => {
                            mp3Attrs.b = 10**8
                            return mp3Attrs
                        })
                    }}
                >clear
                </div>
            </div>
            {/*<div className={"flex flex-row flex-wrap m-10"}>*/}
            {/*    {mp3.lyric.map(paragraph => {*/}
            {/*        return (*/}
            {/*            <div className={"flex flex-row flex-wrap"}>{*/}
            {/*                paragraph.words.map(word => {*/}
            {/*                    return (*/}
            {/*                        <div className={"pl-2"}*/}
            {/*                            onClick={()=>{*/}
            {/*                                setDom({type:"word",pram:word})*/}
            {/*                                setIsOnclick(Math.random)*/}
            {/*                            }}*/}
            {/*                        >*/}
            {/*                            {word.word}*/}
            {/*                        </div>)*/}
            {/*                })*/}
            {/*            }</div>*/}
            {/*        )*/}
            {/*    })}*/}
            {/*</div>*/}
        </div>
    );
};

